package cn.seaboot.admin.logger.manager;

import cn.seaboot.admin.logger.service.AccessLogService;
import cn.seaboot.admin.logger.service.ServiceLogService;
import cn.seaboot.admin.mvc.async.AsyncExecutor;
import cn.seaboot.admin.user.bean.User;
import cn.seaboot.admin.user.context.UserContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * 服务层函数调用日志
 *
 * @author Mr.css
 * @version 2020-09-10 15:56
 */
@Aspect
@Configuration
public class ServiceLoggerAspect {

    @Resource
    private AsyncExecutor asyncExecutor;

    @Resource
    private ServiceLogService serviceLogService;

    @Resource
    private UserContext userContext;

    /**
     * 日志切面
     *
     * @param joinPoint 植入点
     * @return 程序运行结果
     * @throws Throwable 异常
     */
    @Around("@annotation(cn.seaboot.admin.logger.manager.ActionLogger)")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        User user = userContext.getUser();
        try {
            Object ret = joinPoint.proceed();
            this.asyncExecutor.execute(new LoggerRunnable(joinPoint, serviceLogService, user, ret));
            return ret;
        } catch (Exception e) {
            this.asyncExecutor.execute(new LoggerRunnable(joinPoint, serviceLogService, user, e));
            throw e;
        }
    }
}
